import type { AxiosRequestConfig } from 'axios'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useAuthStore } from '@/store/modules/auth'

const instanceHttp = axios.create({
  baseURL: import.meta.env.VITE_PROXY_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 3000,
})
instanceHttp.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    config.headers.Authorization = `Bearer ${authStore.Token.value}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

instanceHttp.interceptors.response.use(
  (response) => {
    if (response.status === 200 || response.status === 201) {
      return Promise.resolve(response.data)
    }
    return Promise.reject(response.data)
  },
  (error) => {
    errorHandle(error)
  },
)
function errorHandle(error: any) {
  const authStore = useAuthStore()
  switch (error?.response?.status) {
    case 401:
      ElMessage.error(error.response.data.message)
      authStore.removeToken()
      router.push({ path: '/login' })
      return Promise.reject(error)
    case 403:
      ElMessage.error(error.response.data.message)
      router.push({ path: '/403' })
      return Promise.reject(error)
    case 404:
      ElMessage.error(error.response.data.message)
      router.push({ path: '/404' })
      return Promise.reject(error)
    case 500:
      ElMessage.error(error.response.data.message)
      return Promise.reject(error)
    default:
      ElMessage.error(error.response.data.message)
      return Promise.reject(error)
  }
}
export function request<T>(config: AxiosRequestConfig = {}): Promise<{
  code: number
  data: T
  message: string
}> {
  // 确保config是一个有效的对象
  return instanceHttp({
    ...config,
  })
}
